package org.ricks.net.json;

import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class JsonParser {
    private final char[] jsonChars;
    private int index;
    private char currentChar;
    // 字段映射缓存（提升性能）
    private static final Map<Class<?>, Map<String, FieldInfo>> FIELD_MAP_CACHE = new ConcurrentHashMap<>();
    // 集合接口默认实现类映射
    private static final Map<Class<?>, Class<?>> DEFAULT_IMPLEMENTATIONS = new HashMap<>();
    static {
        DEFAULT_IMPLEMENTATIONS.put(List.class, ArrayList.class);
        DEFAULT_IMPLEMENTATIONS.put(Set.class, HashSet.class);
        DEFAULT_IMPLEMENTATIONS.put(Collection.class, ArrayList.class);
        DEFAULT_IMPLEMENTATIONS.put(Queue.class, LinkedList.class);
        DEFAULT_IMPLEMENTATIONS.put(Map.class, HashMap.class); // 添加Map的默认实现
    }

    public JsonParser(String json) {
        this.jsonChars = json.toCharArray();
        this.index = 0;
        advance();
    }


    // 序列化字段缓存 (提升性能)
    private static final Map<Class<?>, List<FieldInfo>> SERIALIZE_FIELD_CACHE = new ConcurrentHashMap<>();

    // ========== 新增Map解析功能 ==========
    private Map<String, Object> parseMap(Type mapType) {
        advance(); // 跳过 '{'
        Map<String, Object> map = createMapInstance(mapType);

        // 提取Map的值类型
        Type valueType = Object.class;
        if (mapType instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) mapType;
            Type[] typeArgs = pt.getActualTypeArguments();
            if (typeArgs.length > 1) {
                valueType = typeArgs[1]; // 获取Map的值类型
            }
        }

        skipWhitespace();
        if (currentChar == '}') {
            advance(); // 空对象
            return map;
        }

        while (true) {
            // 解析key
            String key = parseString(String.class);
            skipWhitespace();
            if (currentChar != ':') {
                throw new JsonParseException("Expected ':' after key in map");
            }
            advance(); // 跳过 ':'
            skipWhitespace();

            // 解析value
            Object value = parseValue(null, valueType);
            map.put(key, value);

            skipWhitespace();
            if (currentChar == '}') {
                break;
            } else if (currentChar == ',') {
                advance();
                skipWhitespace();
                // 处理尾随逗号
                if (currentChar == '}') break;
            } else {
                throw new JsonParseException("Expected ',' or '}' after map entry");
            }
        }
        advance(); // 跳过 '}'
        return map;
    }

    // 创建Map实例（支持自定义实现类）
    private Map<String, Object> createMapInstance(Type mapType) {
        Class<?> rawType = getRawType(mapType);
        if (rawType == null || rawType == Object.class) {
            rawType = LinkedHashMap.class; // 默认实现
        }

        // 处理接口类型
        if (rawType.isInterface()) {
            Class<?> impl = DEFAULT_IMPLEMENTATIONS.get(rawType);
            if (impl != null) {
                rawType = impl;
            } else {
                rawType = LinkedHashMap.class; // 默认使用LinkedHashMap
            }
        }

        try {
            return (Map<String, Object>) rawType.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new JsonParseException("Cannot create map instance: " + rawType.getName(), e);
        }
    }

    // ========== 新增序列化方法 ==========
    public static String toJson(Object obj) {
        if (obj == null) return "null";
        StringBuilder sb = new StringBuilder(512); // 预设容量减少扩容
        serializeValue(obj, sb, new IdentityHashMap<>());
        return sb.toString();
    }

    private static void serializeValue(Object obj, StringBuilder sb, Map<Object, Object> seen) {
        if (obj == null) {
            sb.append("null");
            return;
        }

        Class<?> clazz = obj.getClass();

        // 处理基本类型和常见类型
        if (obj instanceof String) {
            escapeString((String) obj, sb);
        } else if (obj instanceof Number || obj instanceof Boolean) {
            sb.append(obj);
        } else if (clazz.isArray()) {
            serializeArray(obj, sb, seen);
        } else if (obj instanceof Collection) {
            serializeCollection((Collection<?>) obj, sb, seen);
        } else if (obj instanceof Map) {
            serializeMap((Map<?, ?>) obj, sb, seen);
        } else if (obj instanceof Enum) {
            escapeString(((Enum<?>) obj).name(), sb);
        } else if (clazz == Character.class || clazz == Character.TYPE) {
            escapeString(obj.toString(), sb);
        } else {
            // 处理自定义对象（带循环引用检测）
            if (seen.containsKey(obj)) {
                throw new JsonSerializeException("Circular reference detected: " + obj);
            }
            seen.put(obj, null);
            serializeObject(obj, sb, seen);
            seen.remove(obj);
        }
    }

    // ========== 序列化具体实现 ==========
    private static void serializeObject(Object obj, StringBuilder sb, Map<Object, Object> seen) {
        sb.append('{');
        List<FieldInfo> fields = getSerializeFields(obj.getClass());
        boolean firstField = true;

        for (FieldInfo fieldInfo : fields) {
            Field field = fieldInfo.field;
            try {
                Object value = field.get(obj);
                // 跳过null值和特殊字段
                if (value == null || Modifier.isTransient(field.getModifiers())) continue;

                if (!firstField) sb.append(',');
                firstField = false;

                escapeString(field.getName(), sb);
                sb.append(':');
                serializeValue(value, sb, seen);
            } catch (IllegalAccessException e) {
                // 静默处理无法访问的字段
            }
        }
        sb.append('}');
    }

    private static void serializeArray(Object array, StringBuilder sb, Map<Object, Object> seen) {
        sb.append('[');
        int length = Array.getLength(array);
        for (int i = 0; i < length; i++) {
            if (i > 0) sb.append(',');
            serializeValue(Array.get(array, i), sb, seen);
        }
        sb.append(']');
    }

    private static void serializeCollection(Collection<?> collection, StringBuilder sb, Map<Object, Object> seen) {
        sb.append('[');
        Iterator<?> it = collection.iterator();
        for (int i = 0; it.hasNext(); i++) {
            if (i > 0) sb.append(',');
            serializeValue(it.next(), sb, seen);
        }
        sb.append(']');
    }

    private static void serializeMap(Map<?, ?> map, StringBuilder sb, Map<Object, Object> seen) {
        sb.append('{');
        Iterator<? extends Map.Entry<?, ?>> it = map.entrySet().iterator();
        boolean firstEntry = true;

        while (it.hasNext()) {
            Map.Entry<?, ?> entry = it.next();
            Object key = entry.getKey();
            // 跳过非字符串键
            if (!(key instanceof String)) continue;

            if (!firstEntry) sb.append(',');
            firstEntry = false;

            escapeString((String) key, sb);
            sb.append(':');
            serializeValue(entry.getValue(), sb, seen);
        }
        sb.append('}');
    }

    // ========== 工具方法 ==========
    private static void escapeString(String str, StringBuilder sb) {
        sb.append('"');
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            switch (c) {
                case '"':  sb.append("\\\""); break;
                case '\\': sb.append("\\\\"); break;
                case '\b': sb.append("\\b"); break;
                case '\f': sb.append("\\f"); break;
                case '\n': sb.append("\\n"); break;
                case '\r': sb.append("\\r"); break;
                case '\t': sb.append("\\t"); break;
                default:
                    if (c < 0x20) {
                        sb.append(String.format("\\u%04x", (int) c));
                    } else {
                        sb.append(c);
                    }
            }
        }
        sb.append('"');
    }

    private static List<FieldInfo> getSerializeFields(Class<?> clazz) {
        return SERIALIZE_FIELD_CACHE.computeIfAbsent(clazz, c -> {
            List<FieldInfo> fields = new ArrayList<>();
            Class<?> current = c;
            while (current != null && current != Object.class) {
                for (Field field : current.getDeclaredFields()) {
                    // 跳过静态字段
                    if (!Modifier.isStatic(field.getModifiers())) {
                        field.setAccessible(true);
                        fields.add(new FieldInfo(field));
                    }
                }
                current = current.getSuperclass();
            }
            return Collections.unmodifiableList(fields);
        });
    }

    // ========== 异常类 ==========
    public static class JsonSerializeException extends RuntimeException {
        public JsonSerializeException(String message) {
            super(message);
        }
    }


    private void advance() {
        currentChar = (index < jsonChars.length) ? jsonChars[index++] : '\0';
    }

    /**
     * 解析JSON到Java对象
     */
    public static <T> T parse(String json, Class<T> clazz) {
        return new JsonParser(json).parseValue(clazz, null);
    }

    /**
     * 支持泛型的解析方法
     */
    public static <T> T parse(String json, TypeReference<T> typeRef) {
        return new JsonParser(json).parseValue(null, typeRef.getType());
    }

    // ========== 核心解析逻辑 ==========
    private <T> T parseValue(Class<T> clazz, Type genericType) {
        skipWhitespace();
        if (currentChar == '{') {
            // 检查是否需要解析为Map
            boolean parseAsMap = false;
            if (clazz != null) {
                parseAsMap = Map.class.isAssignableFrom(clazz) || clazz == Object.class;
            } else if (genericType != null) {
                Class<?> rawType = getRawType(genericType);
                parseAsMap = Map.class.isAssignableFrom(rawType) || rawType == Object.class;
            } else {
                parseAsMap = true; // 默认解析为Map
            }

            if (parseAsMap) {
                return (T) parseMap(genericType);
            } else {
                return parseObject(clazz, genericType);
            }
        } else if (currentChar == '[') {
            return parseArray(clazz, genericType);
        } else if (currentChar == '"') {
            return parseString(clazz);
        } else if (Character.isDigit(currentChar) || currentChar == '-') {
            return parseNumber(clazz);
        } else if (currentChar == 't' || currentChar == 'f') {
            return parseBoolean(clazz);
        } else if (currentChar == 'n') {
            parseNull();
            return null;
        }
        throw new JsonParseException("Unexpected character: " + currentChar + " at position " + index);
    }

    private <T> T parseNumber(Class<T> clazz) {
        int start = index - 1;
        StringBuilder numBuilder = new StringBuilder();
        boolean isDouble = false;

        while (true) {
            if (currentChar == '-' && numBuilder.length() == 0) {
                numBuilder.append(currentChar);
                advance();
            }
            else if (Character.isDigit(currentChar)) {
                numBuilder.append(currentChar);
                advance();
            }
            else if (currentChar == '.' || currentChar == 'e' || currentChar == 'E') {
                isDouble = true;
                numBuilder.append(currentChar);
                advance();
                // 处理指数符号后的正负号
                if (currentChar == '+' || currentChar == '-') {
                    numBuilder.append(currentChar);
                    advance();
                }
            }
            else if (isEndOfNumber()) {
                break;
            }
            else {
                throw new JsonParseException("Invalid number character: " + currentChar);
            }
        }

        String numStr = numBuilder.toString();
        if (numStr.isEmpty()) {
            throw new JsonParseException("Empty number at position " + start);
        }

        try {
            // 处理基本类型和包装类型的统一转换
            if (clazz == null || clazz == Object.class) {
                return handleDefaultNumber(numStr, isDouble);
            } else if (clazz == Integer.TYPE || clazz == Integer.class) {
                return (T) Integer.valueOf(Integer.parseInt(numStr));
            } else if (clazz == Long.TYPE || clazz == Long.class) {
                return (T) Long.valueOf(Long.parseLong(numStr));
            } else if (clazz == Double.TYPE || clazz == Double.class) {
                return (T) Double.valueOf(Double.parseDouble(numStr));
            } else if (clazz == Float.TYPE || clazz == Float.class) {
                return (T) Float.valueOf(Float.parseFloat(numStr));
            } else if (clazz == Short.TYPE || clazz == Short.class) {
                return (T) Short.valueOf(Short.parseShort(numStr));
            } else if (clazz == Byte.TYPE || clazz == Byte.class) {
                return (T) Byte.valueOf(Byte.parseByte(numStr));
            } else if (clazz == Boolean.TYPE || clazz == Boolean.class) {
                // 处理数字到布尔值的转换（0=false，非0=true）
                return (T) Boolean.valueOf(!numStr.equals("0"));
            }
            return (T) Double.valueOf(numStr); // 默认返回Double
        } catch (NumberFormatException e) {
            throw new JsonParseException("Invalid number format: " + numStr);
        }
    }

    // 处理默认数字类型推断
    @SuppressWarnings("unchecked")
    private <T> T handleDefaultNumber(String numStr, boolean isDouble) {
        if (isDouble || numStr.contains(".") || numStr.contains("e") || numStr.contains("E")) {
            double doubleValue = Double.parseDouble(numStr);
            if (doubleValue == (int) doubleValue) {
                return (T) Integer.valueOf((int) doubleValue);
            }
            return (T) Double.valueOf(doubleValue);
        } else {
            try {
                long longValue = Long.parseLong(numStr);
                if (longValue <= Integer.MAX_VALUE && longValue >= Integer.MIN_VALUE) {
                    return (T) Integer.valueOf((int) longValue);
                }
                return (T) Long.valueOf(longValue);
            } catch (NumberFormatException e) {
                return (T) Double.valueOf(Double.parseDouble(numStr));
            }
        }
    }

    // 获取原始类型
    private static Class<?> getRawType(Type type) {
        if (type instanceof Class) return (Class<?>) type;
        if (type instanceof ParameterizedType) return (Class<?>) ((ParameterizedType) type).getRawType();
        return Object.class;
    }

    // 创建实例
    private static <T> T newInstance(Class<T> clazz) {
        try {
            // 尝试使用无参构造函数
            return clazz.getDeclaredConstructor().newInstance();
        } catch (NoSuchMethodException e) {
            // 处理没有无参构造函数的情况
            try {
                Constructor<?>[] constructors = clazz.getDeclaredConstructors();
                for (Constructor<?> constructor : constructors) {
                    if (constructor.getParameterCount() == 0) continue;
                    constructor.setAccessible(true);
                    Class<?>[] paramTypes = constructor.getParameterTypes();
                    Object[] params = new Object[paramTypes.length];
                    for (int i = 0; i < paramTypes.length; i++) {
                        params[i] = getDefaultValue(paramTypes[i]);
                    }
                    return (T) constructor.newInstance(params);
                }
            } catch (Exception ex) {
                throw new RuntimeException("Cannot instantiate class: " + clazz.getName(), ex);
            }
            throw new RuntimeException("No suitable constructor found for: " + clazz.getName());
        } catch (Exception e) {
            throw new RuntimeException("Cannot instantiate class: " + clazz.getName(), e);
        }
    }

    // 获取字段映射表（包含泛型信息）使用缓存提升性能
    private static Map<String, FieldInfo> getFieldMap(Class<?> clazz) {
        return FIELD_MAP_CACHE.computeIfAbsent(clazz, c -> {
            Map<String, FieldInfo> fieldMap = new HashMap<>();
            Class<?> current = c;
            while (current != null && current != Object.class) {
                for (Field field : current.getDeclaredFields()) {
                    fieldMap.put(field.getName(), new FieldInfo(field));
                }
                current = current.getSuperclass();
            }
            return fieldMap;
        });
    }

    // ========== 对象解析 ==========
    private <T> T parseObject(Class<T> clazz, Type genericType) {
        advance(); // 跳过 '{'
        Class<?> rawType = getRawType(genericType);
        if (clazz == null && genericType != null) {
            clazz = (Class<T>) rawType;
        }
        T instance = newInstance(clazz != null ? clazz : (Class<T>) rawType);
        Map<String, FieldInfo> fieldMap = getFieldMap(instance.getClass());

        skipWhitespace();
        if (currentChar == '}') {
            advance(); // 空对象
            return instance;
        }

        while (true) {
            // 解析key
            String key = parseString(String.class);
            // 解析value后添加位置检查
            skipWhitespace();
            if (currentChar == '\0') {
                throw new JsonParseException("Unexpected end of input after field: " + key);
            }
            if (currentChar != ':') throw new JsonParseException("Expected ':'");
            advance(); // 跳过 ':'
            skipWhitespace();
            // 解析value
            FieldInfo fieldInfo = fieldMap.get(key);
            if (fieldInfo != null) {
                Object value = parseValue(fieldInfo.field.getType(), fieldInfo.genericType);
                setFieldValue(instance, fieldInfo, value);
            } else {
                skipValue(); // 跳过未识别的字段
            }
            // 处理逗号分隔
            skipWhitespace();
            if (currentChar == '}') {
                break;
            } else if (currentChar == ',') {
                advance();
                skipWhitespace();
                // 处理尾随逗号
                if (currentChar == '}') break;
            } else if (currentChar == '\0') {
                throw new JsonParseException("Unexpected end of input");
            } else {
                throw new JsonParseException("Expected ',' or '}'");
            }
        }
        advance();
        return instance;
    }

    // ========== 数组/集合解析 ==========
    @SuppressWarnings("unchecked")
    private <T> T parseArray(Class<T> clazz, Type genericType) {
        advance(); // 跳过 '['
        List<Object> list = new ArrayList<>();
        Type elementType = getElementType(clazz, genericType);

        skipWhitespace();
        if (currentChar == ']') {
            advance(); // 空数组
            return (T) Collections.emptyList();
        }

        while (true) {
            list.add(parseValue(null, elementType));
            skipWhitespace();

            if (currentChar == ',') {
                advance();
                skipWhitespace();
            } else if (currentChar == ']') {
                break;
            } else if (currentChar == '\0') {
                throw new JsonParseException("Unexpected end of input");
            }
        }
        if (currentChar == ']') advance();

        // 转换为目标类型
        if (clazz != null && clazz.isArray()) {
            return (T) toArray(list, clazz.getComponentType());
        } else if (clazz != null && Collection.class.isAssignableFrom(clazz)) {
            return (T) toCollection(list, clazz);
        }
        return (T) list;
    }

    // ========== 基础类型解析 ==========
    private <T> T parseString(Class<T> clazz) {
        StringBuilder sb = new StringBuilder();
        advance(); // 跳过起始引号
        while (currentChar != '"' && currentChar != '\0') {
            if (currentChar == '\\') {
                advance(); // 处理转义字符
                switch (currentChar) {
                    case '"': sb.append('"'); break;
                    case '\\': sb.append('\\'); break;
                    case '/': sb.append('/'); break;
                    case 'b': sb.append('\b'); break;
                    case 'f': sb.append('\f'); break;
                    case 'n': sb.append('\n'); break;
                    case 'r': sb.append('\r'); break;
                    case 't': sb.append('\t'); break;
                    case 'u': // Unicode转义
                        if (index + 4 > jsonChars.length) {
                            throw new JsonParseException("Incomplete unicode escape");
                        }
                        String hex = new String(jsonChars, index, 4);
                        index += 4;
                        sb.append((char) Integer.parseInt(hex, 16));
                        currentChar = (index < jsonChars.length) ? jsonChars[index] : '\0';
                        break;
                    default:
                        throw new JsonParseException("Invalid escape sequence: \\" + currentChar);
                }
            } else {
                sb.append(currentChar);
            }
            advance();
        }
        if (currentChar == '"') advance();
        return clazz.cast(sb.toString());
    }

    private boolean isEndOfNumber() {
        return currentChar == '\0' ||
                currentChar == ',' ||
                currentChar == ']' ||
                currentChar == '}' ||
                Character.isWhitespace(currentChar);
    }

    @SuppressWarnings("unchecked")
    private <T> T parseBoolean(Class<T> clazz) {
        if (currentChar == 't') {
            matchKeyword("true");
            // 根据目标类型返回适当的值
            if (clazz != null && clazz == Boolean.TYPE) {
                return (T) Boolean.TRUE; // 自动拆箱
            }
            return (T) Boolean.TRUE;
        } else {
            matchKeyword("false");
            if (clazz != null && clazz == Boolean.TYPE) {
                return (T) Boolean.FALSE; // 自动拆箱
            }
            return (T) Boolean.FALSE;
        }
    }

    private void parseNull() {
        matchKeyword("null");
    }

    // ========== 工具方法 ==========
    private void skipWhitespace() {
        while (Character.isWhitespace(currentChar)) advance();
    }

    private void matchKeyword(String keyword) {
        for (int i = 0; i < keyword.length(); i++) {
            if (currentChar != keyword.charAt(i)) {
                throw new JsonParseException("Expected: " + keyword);
            }
            advance();
        }
    }

    private void skipValue() {
        int depth = 0;
        do {
            if (currentChar == '{' || currentChar == '[') depth++;
            else if (currentChar == '}' || currentChar == ']') depth--;
            advance();
        } while (depth > 0 && currentChar != '\0');
    }


    // ========== 反射工具方法 ==========
    private static Object getDefaultValue(Class<?> type) {
        if (type == boolean.class) return false;
        if (type == byte.class) return (byte) 0;
        if (type == short.class) return (short) 0;
        if (type == int.class) return 0;
        if (type == long.class) return 0L;
        if (type == float.class) return 0.0f;
        if (type == double.class) return 0.0;
        if (type == char.class) return '\0';
        return null;
    }

    private void setFieldValue(Object instance, FieldInfo fieldInfo, Object value) {
        try {
            Class<?> fieldType = fieldInfo.field.getType();
            Class<?> valueType = (value != null) ? value.getClass() : null;

            // 处理基本类型和包装类型的转换
            if (fieldType.isPrimitive() && value != null) {
                setPrimitiveField(instance, fieldInfo, value, fieldType);
                return;
            }

            // 处理枚举类型
            if (fieldType.isEnum() && value instanceof String) {
                Object enumValue = Enum.valueOf((Class<Enum>) fieldType, (String) value);
                fieldInfo.field.set(instance, enumValue);
                return;
            }

            // 处理类型兼容的赋值
            if (value == null || fieldType.isAssignableFrom(valueType)) {
                fieldInfo.field.set(instance, value);
            } else {
                // 尝试数字类型的兼容转换
                if (Number.class.isAssignableFrom(valueType) && Number.class.isAssignableFrom(fieldType)) {
                    Number number = (Number) value;
                    if (fieldType == Integer.class || fieldType == Integer.TYPE) {
                        fieldInfo.field.set(instance, number.intValue());
                    } else if (fieldType == Long.class || fieldType == Long.TYPE) {
                        fieldInfo.field.set(instance, number.longValue());
                    } else if (fieldType == Double.class || fieldType == Double.TYPE) {
                        fieldInfo.field.set(instance, number.doubleValue());
                    } else if (fieldType == Float.class || fieldType == Float.TYPE) {
                        fieldInfo.field.set(instance, number.floatValue());
                    } else if (fieldType == Short.class || fieldType == Short.TYPE) {
                        fieldInfo.field.set(instance, number.shortValue());
                    } else if (fieldType == Byte.class || fieldType == Byte.TYPE) {
                        fieldInfo.field.set(instance, number.byteValue());
                    } else {
                        fieldInfo.field.set(instance, value);
                    }
                } else {
                    fieldInfo.field.set(instance, value);
                }
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Cannot set field: " + fieldInfo.field.getName(), e);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("Type mismatch for field " + fieldInfo.field.getName() +
                    ": expected " + fieldInfo.field.getType() +
                    ", got " + (value != null ? value.getClass() : "null"), e);
        }
    }

    // 设置基本类型字段的值
    private void setPrimitiveField(Object instance, FieldInfo fieldInfo, Object value, Class<?> fieldType)
            throws IllegalAccessException {
        if (value instanceof Number) {
            Number number = (Number) value;
            if (fieldType == int.class) {
                fieldInfo.field.setInt(instance, number.intValue());
            } else if (fieldType == long.class) {
                fieldInfo.field.setLong(instance, number.longValue());
            } else if (fieldType == double.class) {
                fieldInfo.field.setDouble(instance, number.doubleValue());
            } else if (fieldType == float.class) {
                fieldInfo.field.setFloat(instance, number.floatValue());
            } else if (fieldType == short.class) {
                fieldInfo.field.setShort(instance, number.shortValue());
            } else if (fieldType == byte.class) {
                fieldInfo.field.setByte(instance, number.byteValue());
            } else if (fieldType == boolean.class) {
                // 处理数字到布尔值的转换
                fieldInfo.field.setBoolean(instance, number.doubleValue() != 0);
            }
        } else if (value instanceof Boolean) {
            if (fieldType == boolean.class) {
                fieldInfo.field.setBoolean(instance, (Boolean) value);
            }
        } else if (value instanceof Character) {
            if (fieldType == char.class) {
                fieldInfo.field.setChar(instance, (Character) value);
            }
        } else {
            throw new IllegalArgumentException("Cannot assign " + value.getClass() +
                    " to primitive field " + fieldInfo.field.getName());
        }
    }

    private static Object toArray(List<Object> list, Class<?> componentType) {
        Object array = Array.newInstance(componentType, list.size());
        for (int i = 0; i < list.size(); i++) {
            Array.set(array, i, list.get(i));
        }
        return array;
    }

    @SuppressWarnings("unchecked")
    private static Collection<Object> toCollection(List<Object> list, Class<?> collectionClass) {
        try {
            // 处理接口类型，使用默认实现
            if (collectionClass.isInterface()) {
                Class<?> implClass = DEFAULT_IMPLEMENTATIONS.get(collectionClass);
                if (implClass == null) {
                    throw new IllegalArgumentException("No default implementation for interface: " + collectionClass.getName());
                }
                collectionClass = implClass;
            }
            // 尝试通过无参构造函数创建集合实例
            Collection<Object> collection = (Collection<Object>) collectionClass.getDeclaredConstructor().newInstance();
            collection.addAll(list);
            return collection;
        } catch (Exception e) {
            throw new RuntimeException("Cannot create collection: " + collectionClass.getName(), e);
        }
    }

    private Type getElementType(Class<?> clazz, Type genericType) {
        if (clazz != null && clazz.isArray()) {
            return clazz.getComponentType();
        }
        if (genericType instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) genericType;
            Type[] actualTypeArguments = pt.getActualTypeArguments();
            if (actualTypeArguments.length > 0) {
                return actualTypeArguments[0];
            }
        }
        return Object.class;
    }

    // ========== 异常类 ==========
    public static class JsonParseException extends RuntimeException {
        public JsonParseException(String message) {
            super(message);
        }

        public JsonParseException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    // ========== TypeReference ==========
    public static abstract class TypeReference<T> {
        private final Type type;
        protected TypeReference() {
            Type superClass = getClass().getGenericSuperclass();
            if (superClass instanceof Class) {
                throw new IllegalArgumentException("TypeReference must be parameterized");
            }
            this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
        }
        public Type getType() {
            return type;
        }
    }

    // 字段信息封装类
    private static class FieldInfo {
        final Field field;
        final Type genericType;

        FieldInfo(Field field) {
            this.field = field;
            this.field.setAccessible(true);
            this.genericType = field.getGenericType();
        }
    }
}
